//
//  ModifyManagerViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/29.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "ModifyManagerViewController.h"
#import "RelationShipViewController.h"
#import "DeleteManagerViewController.h"

#import "AppDelegate.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
@interface ModifyManagerViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,retain) UITapGestureRecognizer *tapReconizerToRelation;

@end

@implementation ModifyManagerViewController
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize relationShipView;
@synthesize relationShipLabel;
@synthesize avatarImageView;
@synthesize birthDayView;
@synthesize birthDayLabel;
@synthesize managerTypeLabel;
@synthesize phoneNumberLabel;
@synthesize nicknameLabel;

@synthesize transferOrDeleteButton;

@synthesize managersArray;
@synthesize relationString;
@synthesize relationDistance;
@synthesize nextImage;
-(void)dealloc
{
    self.managersArray=NULL;
    self.relationString=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.tapReconizerToRelation=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"成员信息";
    self.navigationItem.rightBarButtonItem=navRightButton;
    
    
    [self initNavButton];
    [self initData];
    [self initViewAction];
    [self initDataProxy];
    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
    relationShipLabel.text=relationString;
    AppDelegate *mydelegate=[[UIApplication sharedApplication ] delegate];

    
    //判断是不是自己
    Manager *manager=managersArray;
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    BOOL v=NO;
//    if (userId==manager.user_id)
//    {
//        v=YES;
//    }
    if(mydelegate.isAdmin==YES)
    {
        //转移主管理员功能暂时没有
        //self.transferOrDeleteButton.hidden=YES;
    }
    if(mydelegate.isAdmin==NO)
    {
        self.transferOrDeleteButton.hidden=YES;
        if (manager.type==1)
        {
            v=YES;
        }
    }
    if (v)
    {
        self.nextImage.hidden=YES;
        self.relationDistance.constant=0;
        [self.relationShipView removeGestureRecognizer:self.tapReconizerToRelation];
        self.navigationItem.rightBarButtonItem=NULL;
        self.transferOrDeleteButton.enabled=NO;
        self.transferOrDeleteButton.hidden=YES;
    }
    else
    {
        if ((managersArray.type==2)&&(![userId isEqualToString:manager.user_id]))
        {
            self.nextImage.hidden=YES;
            self.relationDistance.constant=0;
            [self.relationShipView removeGestureRecognizer:self.tapReconizerToRelation];
            self.navigationItem.rightBarButtonItem=NULL;
        }
    }
    
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    self.nextImage.hidden=NO;
    self.relationDistance.constant=15;
    [self.relationShipView addGestureRecognizer:self.tapReconizerToRelation];
    self.navigationItem.rightBarButtonItem=navRightButton;
}
-(void)initViewAction
{
//    UIButton *relationButton=[[UIButton alloc]initWithFrame:relationShipView.frame];
//    [relationShipView addSubview:relationButton];
//    [relationButton addTarget:self action:@selector(relationAction) forControlEvents:UIControlEventTouchDown];
    
    //进入关系修改手势
    self.tapReconizerToRelation = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(relationAction)];
    [self.relationShipView addGestureRecognizer:self.tapReconizerToRelation];


    
}
-(void)relationAction
{
    RelationShipViewController *relationController=[[RelationShipViewController alloc]init];
    relationController.lastViewController=self;
    relationController.origianlRelation=relationString;
    [self. navigationController pushViewController:relationController animated:YES];
}
- (void)initNavButton {
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(save)];
    
}

-(void) transferManager
{
//    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
//    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    DeleteManagerViewController *deleteMVC=[[DeleteManagerViewController alloc]init];
//    [deleteMVC setMotherWindow:alertView];
//    alertView.rootViewController=deleteMVC;
//    [keyWindow addSubview:alertView];
//    [alertView setWindowLevel:UIWindowLevelAlert];
//    [alertView makeKeyAndVisible];
}
-(void) deleteManager
{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    DeleteManagerViewController *deleteMVC=[[DeleteManagerViewController alloc]init];
    [deleteMVC setMotherWindow:alertView];
    alertView.rootViewController=deleteMVC;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    [deleteMVC.confirmButton addTarget:self action:@selector(confirmDeleteViceManage) forControlEvents:UIControlEventTouchDown];

}
-(void)confirmDeleteViceManage
{
    self.transferOrDeleteButton.enabled=NO;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    NSString *deviceUid=watchId;
    
    Manager *manager=managersArray;
    NSString *viceAdmin=manager.user_id;
    [self .syncManager deleteViceAdmin:deviceUid viceAdminUid:viceAdmin completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        //[self callback:result retValue:retValue description:description];
        
        if(result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            NSLog(@"%@,syncFromServer,syncManager is null.",TAG);
            [Tooler showHttpMsg:result description:description msg:@"删除副管理员失败"];
            self.transferOrDeleteButton.enabled=YES;
            return ;

        }

    }];

}
- (void)initData {

    Manager *manager=managersArray;
    self.relationShipLabel.text=manager.alias;
    relationString=manager.alias;
    User *user=[User sharedSingleton];
    if(user!=NULL&&[user.uid isEqualToString:manager.user_id])
    {
        avatarImageView.image=[UIImage imageNamed:@"avater_other"];
        if(user.pic_url!=NULL&&![user.pic_url isEqualToString:@"(null)"]&&![user.pic_url isEqualToString:@""])
        {
            avatarImageView.image=[UIImage imageNamed:[[Tooler getDocumentDirectory] stringByAppendingString:user.pic_url]];
        }
        else
        {
            
            DataManager *dataManager=[[DataManager alloc]init];
            Manager *userManager=[dataManager getManagerByUid:user.uid];
            if(userManager.pic_url!=NULL&&![userManager.pic_url isEqualToString:@"(null)"]&&![userManager.pic_url isEqualToString:@""])
            {
                NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],userManager.pic_url];
                avatarImageView.image=[UIImage imageWithContentsOfFile:headUrl];
            }

//            Manager *manager=[self.dataManager getManagerByUid:user.uid];
//            if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
//            {
//                avatarImageView.image=[UIImage imageNamed:[[Tooler getDocumentDirectory] stringByAppendingString:manager.pic_url]];
//            }

        }
        
        if(user.birth!=NULL&&![user.birth isEqualToString:@"(null)"]&&![user.birth isEqualToString:@""])
        {
            //birthDayLabel.text=user.birth;
            birthDayLabel.text=[Tooler second2Stringformat:user.birth withFormatter:@"yyyy-MM-dd"];
        }
        else
        {
            if(manager!=NULL&& manager.birth!=NULL&&![manager.birth isEqualToString:@"(null)"])
            {
                //nicknameLabel.text=manager.birth;
                birthDayLabel.text=[Tooler second2Stringformat:manager.birth withFormatter:@"yyyy-MM-dd"];
            }
            else
            //birthDayLabel.text=manager.birth;
            {
            birthDayLabel.text=@"未设置";
            

            }
        }
        phoneNumberLabel.text=user.account;
        if(user.nickName!=NULL&&![user.nickName isEqualToString:@"(null)"]&&![user.nickName isEqualToString:@""])
        {
            
            nicknameLabel.text=user.nickName;
        }
        else
        {
            if(manager!=NULL&& manager.nickName!=NULL&&![manager.nickName isEqualToString:@"(null)"])
            {
                nicknameLabel.text=manager.nickName;
            }
            else
            {
            //nicknameLabel.text=manager.nickName;
            nicknameLabel.text=@"未设置";
            }
        }
    }
    else
    {
        if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
        {
            avatarImageView.image=[UIImage imageNamed:[[Tooler getDocumentDirectory] stringByAppendingString:manager.pic_url]];
        }
        else
        {
            avatarImageView.image=[UIImage imageNamed:@"avater_other"];
        }
        
        if(manager.birth!=NULL&&![manager.birth isEqualToString:@"(null)"]&&![manager.birth isEqualToString:@""])
        {
            birthDayLabel.text=[Tooler second2Stringformat:manager.birth withFormatter:@"yyyy-MM-dd"];
            //birthDayLabel.text=manager.birth;
        }
        else{birthDayLabel.text=@"未设置";};

        //birthDayLabel.text=manager.birth;
        phoneNumberLabel.text=manager.phone;
        //nicknameLabel.text=manager.nickName;
        if(manager.nickName!=NULL&&![manager.nickName isEqualToString:@"(null)"]&&![manager.nickName isEqualToString:@""])
        {
            nicknameLabel.text=manager.nickName;
        }
        else{nicknameLabel.text=@"未设置";}

    }
    self.avatarImageView.layer.cornerRadius = self.avatarImageView.frame.size.width / 2;
    self.avatarImageView.clipsToBounds = YES;
    if (manager.type==1)
    {
        managerTypeLabel.text=@"主管理员";
        [transferOrDeleteButton addTarget:self action:@selector(transferManager) forControlEvents:UIControlEventTouchDown];
        //转移主管理员暂时没有
        transferOrDeleteButton.hidden=YES;
        
    }
    else
    {
        managerTypeLabel.text=@"副管理员";
        [transferOrDeleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [transferOrDeleteButton addTarget:self action:@selector(deleteManager) forControlEvents:UIControlEventTouchDown];
    }
    
}

- (void)save{
    
//
//    User *user=[User sharedSingleton];
//    user.email=@"315261347@qq.com";
//    user.birth=@"1985-04-03";
//    user.age=30;
//    user.address=@"jincheng";
//    user.nickName=@"yan";
//    user.pic_url=[[NSBundle bundleForClass:[self class]] pathForResource:@"avater_boy" ofType:@"png"];
//    user.photoName=@"avater_boy.png";
//    [self.syncManager setUserInfo:^(SyncResult result, NSDictionary *retValue, NSString *description) {
//        
//    }];


    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    [self.syncManager updateRelation:watchId alias:relationShipLabel.text completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            [LeoMsg showMsg:@"修改成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {            
            [Tooler showHttpMsg:result description:description msg:@"关系修改失败"];
            NSLog(@"%@",description);
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
-(void)getAccountData{
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    //    Watch *watch=[self.dataManager getActiveWatch:userId];
    //    NSString *watchId=watch.deviceUid;
    //    self.watch=watch;

    
    
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
